<?php

namespace app\admin\controller\goods;

use app\admin\controller\goodscommon\Goodscommon;
use app\common\controller\Backend;

/**
 * 商品管理
 *
 * @icon fa fa-circle-o
 */
class Goods extends Backend
{
    
    /**
     * Goods模型对象
     * @var \app\admin\model\Goods
     */
    protected $model = null;
    protected $relationSearch=true;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Goods;
        $this->view->assign("goodsVerifyList", $this->model->getGoodsVerifyList());
        $this->view->assign("goodsCommendList", $this->model->getGoodsCommendList());
        $this->view->assign("sourceList", $this->model->getSourceList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index($ids=null)
    {
        $ids=input('ids');

        // halt($ids);
        if(empty($ids)){
            $ids=session('ids');

        }else{
            session('ids',$ids);

        }
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $cond['goods_common_id']=$ids;
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where($cond)
                ->with('classes')
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->where($cond)
                ->with('classes')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $is_has_goods=model('Goodscommon')->where(['id'=>$ids])->value('is_has_goods');
        $this->assign('has',$is_has_goods);
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        $ids=session('ids');

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $is_has_goods=model('Goodscommon')->where(['id'=>$ids])->value('is_has_goods');
                if($is_has_goods==1){
                    $this->error('商品没有清空，您还不能生成');
                }
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $goods_common=new Goodscommon();
                    //halt($ids);
                    $arr=model('Goodscommon')->where(['id'=>$ids])->find();

                    $arr['spec_attr']=$params['spec_attr'];
                   // $arr['attrId']=$params['attrId'];

                    #修改商品公共表
                    $res=model('Goodscommon')
                        ->where(['id'=>$ids])
                        ->update(['spec_value_ids'=>json_encode($params['spec_attr']),'is_has_goods'=>1,'updatetime'=>date('YmdHIs')]);
                    #生成商品SKU

                    $result=$goods_common->addSku($arr,$ids);
                   // $result = $this->model->allowField(true)->save($params);
                    if ($result !== false && $res!==false) {
                        $this->success('添加成功');
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage()).$e->getLine();
                }
            }

            $this->error(__('Parameter %s can not be empty', ''));
        }

        $class_id=model('Goodscommon')->where(['id'=>$ids])->value('classes_id');

        $data=model('Classattr')->where(['classes_id'=>$class_id])->select();

        $this->assign('data',$data);
        $this->assign('class_id',$class_id);

        return $this->view->fetch();
    }
    /**
     * 删除
     */
    public function del($ids = "")
    {
        $ids=session('ids');
        if ($ids) {
           /* $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }*/
            $list = $this->model->where(['goods_common_id'=>$ids])->select();
            //halt($list);
            $count = 0;
            foreach ($list as $k => $v) {
                $count += $v->delete();
            }
            if ($count) {
                $is_has=model('Goodscommon')->where(['id'=>$ids])->update(['is_has_goods'=>2,'status'=>1,'goods_verify'=>3,'updatetime'=>date('Y-m-d H:i:s')]);
                if($is_has){
                    $this->success();
                }else{
                    $this->error(__('No rows were deleted'));
                }

            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['goods_image']=SHOPURL.$params['goods_image'];
            if ($params) {
                try {
                    $params['updatetime']=date('YmdHis');
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    //    $storage=model('Goodscommon')->where(['id'=>$params['goods_common_id']])->value('storage');
                    $storage=$params['storage']-$row['storage'];
                    //  $storage=$storage+$params['storage'];
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        if($params['storage']>0){

                            $res=model('Goodscommon')->where(['id'=>$params['goods_common_id']])->setInc('storage',$storage);
                            if($res !== false){
                                $this->success();
                            }else{
                                $this->error($row->getError());
                            }
                        }
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
      //  $row['goods_image']=str_replace(SHOPURL,'',$row['goods_image']);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


}
